package com.baselibrary.net;

import androidx.activity.ComponentActivity;
import androidx.annotation.StringRes;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Lifecycle;
import androidx.lifecycle.OnLifecycleEvent;

import com.baselibrary.R;
import com.baselibrary.net.result.HttpResult;
import com.baselibrary.utils.ContextUtils;
import com.baselibrary.utils.HKToastUtils;
import com.baselibrary.utils.SpUtils;
import com.google.gson.stream.MalformedJsonException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketTimeoutException;

import io.reactivex.Observer;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;

/**
 * @author zhanglijie
 * @date 2020/4/9
 * @Description
 */
public abstract class APIResponse<T> implements Observer<HttpResult<T>>, androidx.lifecycle.LifecycleObserver {
    private static final Object TAG = APIResponse.class.getSimpleName();

    private Disposable mDisposable;
    private boolean isDestroy;
    private Object mTag;


    public APIResponse(Object tag) {
        mTag = tag;
    }

    public <T> T getTag() {
        return (T) mTag;
    }

    public APIResponse(Fragment fragment) {
        fragment.getLifecycle().addObserver(this);
    }

    public APIResponse(ComponentActivity activity) {
        activity.getLifecycle().addObserver(this);
    }

    public abstract void onSuccess(T result, String json);

    protected void onFailed(String message) {
        HKToastUtils.showToast(message);
    }

    @Override
    public void onNext(@NonNull HttpResult<T> t) {
        SpUtils.putBoolean(ContextUtils.getCurApplication(),"network_access",true);
        if (t.isSuccess()) {
            onSuccess(t.getData(),t.getJson());
        } else {
            onFailed(t.getMessage());
        }
    }

    @Override
    public final void onSubscribe(Disposable d) {
        this.mDisposable = d;
    }

    @Override
    public void onError(Throwable e) {
        if (isDestroy) {
            return;
        }

        if (e instanceof SocketTimeoutException) {
            showMessage(R.string.network_time_out);
        } else if (e instanceof ConnectException) {
            SpUtils.putBoolean(ContextUtils.getCurApplication(),"network_access",false);
            showMessage(R.string.network_api_error);
        } else if (e instanceof MalformedJsonException) {
            //返回json数据格式出错
//            showMessage(R.string.data_error);
        } else if (e instanceof JSONException) {
            //json解析出错
//            showMessage(R.string.parse_data_error);
        } else if (e instanceof NumberFormatException) {
//            showMessage(R.string.number_format_error);
        } else {
            SpUtils.putBoolean(ContextUtils.getCurApplication(),"network_access",false);
            showMessage(R.string.network_api_error);
        }
        if (!e.getMessage().startsWith("Unable")) {
            onFailed(e.getMessage());
        }        onComplete();
    }

    @Override
    public final void onComplete() {
        if (isDestroy) {
            return;
        }
        onHttpComplete();
    }

    protected void onHttpComplete() {

    }

    private void showMessage(@StringRes int id) {
        if (isDestroy) {
            return;
        }
        HKToastUtils.showToast(id);
    }

    /**
     * Toast消息
     */
    protected void showMessage(String msg) {
        if (isDestroy) {
            return;
        }
        HKToastUtils.showToast(msg);
    }

    @OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
    public void onDestroy() {
        isDestroy = true;
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        mDisposable = null;
    }
}
